package com.fxz.oauth.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fxz.oauth.domain.Auth;
import com.fxz.oauth.domain.User;
import com.fxz.oauth.domain.dto.LoginDto;
import com.fxz.oauth.domain.dto.UserDto;
import com.fxz.oauth.exception.DuplicateProblem;
import com.fxz.oauth.service.IUserService;
import com.fxz.oauth.util.JwtUtil;
import lombok.AllArgsConstructor;
import lombok.val;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.nio.file.AccessDeniedException;

/**
 * @author Fxz
 * @version 1.0
 * @date 2021-08-03 16:24
 */
@AllArgsConstructor
@RequestMapping("/authorize")
@RestController
public class AuthorizeResource {

    private final IUserService userService;

    private final JwtUtil jwtUtil;

    /**
     * 用户注册
     *
     * @param userDto
     */
    @PostMapping("/register")
    public void register(@Valid @RequestBody UserDto userDto) {
        String username = userDto.getUsername();
        String email = userDto.getEmail();
        String mobile = userDto.getMobile();
        if (userService.getOne(new LambdaQueryWrapper<User>().eq(User::getUsername, username)) != null) {
            throw new DuplicateProblem("用户名重复!");
        }
        if (userService.getOne(new LambdaQueryWrapper<User>().eq(User::getEmail, email)) != null) {
            throw new DuplicateProblem("电子邮件重复!");
        }
        if (userService.getOne(new LambdaQueryWrapper<User>().eq(User::getMobile, mobile)) != null) {
            throw new DuplicateProblem("手机号重复!");
        }
        val user = User.builder()
                .username(userDto.getUsername())
                .name(userDto.getName())
                .email(userDto.getEmail())
                .mobile(userDto.getMobile())
                .password(userDto.getPassword())
                .build();
        userService.register(user);
    }

    /**
     * 获取访问token和刷新token
     */
    @PostMapping("/token")
    public Auth login(@Valid @RequestBody LoginDto loginDto) throws Exception {
        return userService.login(loginDto.getUsername(), loginDto.getPassword());
    }

    @PostMapping("/token/refresh")
    public Auth refreshToken(@RequestHeader(name = "Authorization") String authorization,
                             @RequestParam String refreshToken) throws AccessDeniedException {
        String PREFIX = "Bearer";
        String accessToken = authorization.replace(PREFIX, "");
        if (jwtUtil.validateAccessToken(accessToken) && jwtUtil.validateAccessTokenWithoutExpiration(accessToken)) {
            return new Auth(jwtUtil.createAccessTokenWithRefreshToken(refreshToken), refreshToken);
        }
        throw new AccessDeniedException("访问被拒绝!");
    }
}
